/*
 * Description: 岗位状态中心
 * Company: 联宝（合肥）电子科技有限公司
 * Author: Dongxu.Ni
 * Date: 2020/3/10 18:00
 */
import { postQueryBySession, postListAllSimple, postListSubordinate } from '../../api/sys/post'

const state = {
  // 所有岗位简要信息集合（包含名称电话）
  postSimpleCollects: [],
  // 当前会话岗位信息
  sessionPost: {},
  // 当前岗位下级岗位
  subPostList: []
}

const getters = {
  getSessionPost: state => state.sessionPost,
  getSessionPostId: state => state.sessionPost.postId,
  getSubPostList: state => state.subPostList,
  getSelfAndSubPostList: state => [state.sessionPost].concat(state.subPostList),
  getPostNameById: state => postId => {
    const post = state.postSimpleCollects.find(p => p.postId === postId)
    return post ? post.postName : postId
  }
}

const mutations = {
  SET_SESSION_POST: (state, sessionPost) => {
    state.sessionPost = sessionPost
  },
  SET_POST_SIMPLE_COLLECTS: (state, postSimpleCollects) => {
    state.postSimpleCollects = postSimpleCollects
  },
  SET_SUB_POST_LIST: (state, subPostList) => {
    state.subPostList = subPostList
  }
}

const actions = {
  initSessionPost({ commit, state }) {
    return new Promise((resolve, reject) => {
      postQueryBySession()
        .then(response => {
          commit('SET_SESSION_POST', response.data)
          resolve()
        })
        .catch(err => reject(err))
    })
  },
  initPostSimpleCollects({ commit, state }) {
    return new Promise((resolve, reject) => {
      postListAllSimple()
        .then(response => {
          commit('SET_POST_SIMPLE_COLLECTS', response.data)
          resolve()
        })
        .catch(err => reject(err))
    })
  },
  initSubPostList({ commit, state }) {
    return new Promise((resolve, reject) => {
      postListSubordinate({})
        .then(response => {
          commit('SET_SUB_POST_LIST', response.data)
          resolve()
        })
        .catch(err => reject(err))
    })
  }
}

export default {
  namespaced: true,
  state,
  getters,
  mutations,
  actions
}
